package controller

import (
	"context"
	v1 "gf2DemoServer/api/v1"
	"gf2DemoServer/internal/model"
	"gf2DemoServer/internal/service"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

var (
	Category = cCategory{}
)

type cCategory struct{}

// Add 添加
func (c *cCategory) Add(ctx context.Context, req *v1.CategoryAddReq) (res *v1.CategoryAddRes, err error) {
	insertId := service.Category().Add(ctx, &model.CategoryAddInput{
		Title:  req.Title,
		Thumb:  req.Thumb,
		Sort:   req.Sort,
		Status: req.Status,
	})
	if g.IsEmpty(insertId) {
		return nil, gerror.NewCode(gcode.CodeOperationFailed, "添加失败")
	}
	return nil, gerror.NewCode(gcode.CodeOK, "添加成功")
}

// Del 删除
func (c *cCategory) Del(ctx context.Context, req *v1.CategoryDelReq) (res *v1.CategoryDelRes, err error) {
	status := service.Category().Del(ctx, req.Ids)
	if !status {
		return nil, gerror.NewCode(gcode.CodeOperationFailed, "删除失败")
	}
	return nil, gerror.NewCode(gcode.CodeOK, "删除成功")
}

// Update 修改
func (c *cCategory) Update(ctx context.Context, req *v1.CategoryUpdateReq) (res *v1.CategoryUpdateRes, err error) {
	update := service.Category().Update(ctx, &model.CategoryUpdateInput{
		Id: req.Id,
		CategoryAddInput: &model.CategoryAddInput{
			Title:  req.Title,
			Thumb:  req.Thumb,
			Sort:   req.Sort,
			Status: req.Status,
		},
	})
	if !update {
		return nil, gerror.NewCode(gcode.CodeOperationFailed, "修改失败")
	}
	return nil, gerror.NewCode(gcode.CodeOK, "修改成功")
}

// List 列表
func (c *cCategory) List(ctx context.Context, req *v1.CategoryListReq) (res *v1.CategoryListRes, err error) {
	list, count := service.Category().List(ctx, &model.CategoryListInput{
		Page:  req.Page,
		Limit: req.Limit,
		Title: req.Title,
	})
	res = &v1.CategoryListRes{
		List:  list,
		Count: count,
	}
	return
}

// Detail 修改
func (c *cCategory) Detail(ctx context.Context, req *v1.CategoryDetailReq) (res *v1.CategoryDetailRes, err error) {
	info := service.Category().Detail(ctx, req.Id)
	if g.IsEmpty(info) {
		return nil, gerror.NewCode(gcode.CodeNil, "分类不存在")
	}
	res = &v1.CategoryDetailRes{
		CategoryDetail: info,
	}
	return
}
